<?php
namespace app\admin\controller;

use app\admin\model\User as Users;
use app\BaseController;
use think\facade\View;
use think\facade\Session;
use think\facade\Cookie;

class Login extends BaseController
{
    protected $m;
    protected function initialize()
    {
        parent::initialize();
        $this->m = new Users;   //别名：避免与控制名冲突
        View::assign('site_title', 'tp6');
    }
    
    public function index()
    {
        $uid = Session::get('uid');
        // dump($uid);die;
        if (!empty($uid)){
            return redirect(url('admin/index/index'));
        }else{
            return View::fetch('login/index');
        }
        return View::fetch();
    }
    
    public function checkLogin()
    {
        if(request()->isPost()){
            $data = input('post.');
//            if(!captcha_check($data['code'])){
//                return ajaxReturn(lang('code_error'));
//            };
            $where = ['username' => $data['username'] ];
            $user = $this->m->where($where)->find();
            if(!empty($user)){
                if($user['status'] != '1'){
                    return json(['code' => 404, 'msg' => '用户被禁用', 'data' => null]);
                }elseif($user['password'] != md5($data['password'])){
                    return json(['code' => 404, 'msg' => '密码错误', 'data' => null]);
                }else{
                    session('uid',$user['id']);
                    // 更新登陆信息
                    $ip = request()->ip();
                    $updata = [
                        'logins' => $user['logins']+1,
                        'last_time' => time(),
                        'last_ip' => $ip,
                    ];
                    $where = ['id' => $user['id']];
                    $this->m->where($where)->update($updata);
                    return json(['code' => 0, 'msg' => '登录成功', 'data' => null]);
                }
            }else{
                return json(['code' => 404, 'msg' => '用户不存在', 'data' => null]);
            }
        }
    }
    
    public function loginOut($params='')
    {
         // Session::delete('userId');
         Session::delete('uid');
         Session::delete('user_token');
         Session::clear();
        // Cookie::delete('name');
        // cookie('uname', null);
        // cookie('uid', null);
         Cookie::delete('avatar');
        return redirect(url('/admin/Login/index'));
       
    }
    
    public function restLogin(){
        return $this->fetch();
    }
}
